<?php

namespace app\common\controller;
use OSS\Core\OssException;
use OSS\OssClient;

class OssPolicyGenerator
{
    private $accessKeyId;
    private $accessKeySecret;
    private $bucket;
    private $endpoint;

    public function __construct($accessKeyId, $accessKeySecret, $bucket, $endpoint)
    {
        $this->accessKeyId = $accessKeyId;
        $this->accessKeySecret = $accessKeySecret;
        $this->bucket = $bucket;
        $this->endpoint = $endpoint;
    }

    public function generatePolicy($expire, $dir)
    {
        $policy = [
            'expiration' => $this->gmtIso8601(time() + $expire),
            'conditions' => [
                ['eq', '$bucket', $this->bucket],

                ['content-length-range', 0, 1024000] // 限制文件大小范围100m
            ]
        ];

        return base64_encode(json_encode($policy));
    }

    private function gmtIso8601($time)
    {
        $dtStr = date("c", $time);
        $mydatetime = new \DateTime($dtStr);
        $expiration = $mydatetime->format(\DateTime::ISO8601);
        $pos = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);

        return $expiration . "Z";
    }
}